package com.platform.cdcs.fragment.stock;

import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.platform.cdcs.R;
import com.platform.cdcs.fragment.ProductFragment;
import com.platform.cdcs.fragment.detail.ProductInfoFragment;
import com.platform.cdcs.model.BaseObjResponse;
import com.platform.cdcs.model.HouseItem;
import com.platform.cdcs.model.ProductList;
import com.platform.cdcs.model.RefershEvent;
import com.platform.cdcs.tool.CacheTool;
import com.platform.cdcs.tool.Constant;
import com.platform.cdcs.tool.FragmentUtil;
import com.sherchen.slidetoggleheader.views.ObservableXListView;
import com.sherchen.slidetoggleheader.views.XListView;
import com.trueway.app.uilib.activity.BaseActivity;
import com.trueway.app.uilib.adapter.EnhancedAdapter;
import com.trueway.app.uilib.fragment.BaseFragment;
import com.trueway.app.uilib.model.ChooseItem;
import com.trueway.app.uilib.tool.Utils;
import com.trueway.app.uilib.widget.TwDialogBuilder;
import com.trueway.app.uilib.widget.TwSegmentWidget;
import com.tubb.smrv.SwipeHorizontalMenuLayout;
import com.tubb.smrv.SwipeMenuLayout;
import com.tubb.smrv.listener.SwipeSwitchListener;
import com.zhy.http.okhttp.callback.StringCallback;

import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;

import de.greenrobot.event.EventBus;
import de.greenrobot.event.Subscribe;
import okhttp3.Call;

/**
 * Created by holytang on 2017/9/30.
 */
public class ProductDetailFragment extends BaseFragment {

    private ItemAdapter adapter1;
    private ItemAdapter adapter2;
    private ObservableXListView listView1;
    private ObservableXListView listView2;
    private String whName;
    private ProductList.ProductItem item;
    private int pageIndex1 = 1, pageIndex2 = 1;
    private TextView numView;
    private XListView.OnXScrollListener scrollListener = new XListView.OnXScrollListener() {
        @Override
        public void onXScrolling(View view) {
        }

        @Override
        public void onScrollStateChanged(AbsListView absListView, int i) {

        }

        @Override
        public void onScroll(AbsListView absListView, int i, int i1, int i2) {
            if (listView2.getVisibility() == View.VISIBLE) {
                adapter2.closeSlide();
            } else {
                adapter1.closeSlide();
            }
        }
    };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            item = (ProductList.ProductItem) getArguments().getSerializable("model");
            whName = getArguments().getString("whName");
        }
        EventBus.getDefault().register(this);
        adapter1 = new ItemAdapter(getContext());
        ProductList.ProductItem item = new ProductList.ProductItem();
        item.setItemName("序列号");
        item.setType(1);
        adapter1.addItem(item);
        adapter2 = new ItemAdapter(getContext());
//        item = new ProductList.ProductItem();
//        item.setItemName("批号");
//        item.setType(1);
//        adapter2.addItem(item);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void initView(View view) {
        initLoadImg(view.findViewById(R.id.load));
        ((BaseActivity) getActivity()).getToolBar().setVisibility(View.GONE);
        final TextView titleView = (TextView) view.findViewById(R.id.title);
        final String code = item.getItemCode();
        titleView.setText(code + "\n▽");
        view.findViewById(R.id.button1).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                getActivity().finish();
            }
        });
        view.findViewById(R.id.right_side).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                new TwDialogBuilder(getContext()).setItems(new String[]{"入库", "出库"}, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        Bundle bundle = new Bundle();
                        bundle.putInt("model", i);
                        FragmentUtil.navigateToInNewActivity(getActivity(), EditProductFragment.class, bundle);
                    }
                }, "").create().show();
            }
        });
        numView = (TextView) view.findViewById(R.id.num);
        refershNum();
        final TextView textView = (TextView) view.findViewById(R.id.text);
        textView.setVisibility(View.GONE);
        textView.setText(item.getItemName());

        titleView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (titleView.getText().toString().contains("▽")) {
                    textView.setVisibility(View.VISIBLE);
                    titleView.setText(code + "\n△");
                } else {
                    titleView.setText(code + "\n▽");
                    textView.setVisibility(View.GONE);
                }
            }
        });
        listView1 = (ObservableXListView) view.findViewById(android.R.id.list);
        listView1.setAdapter(adapter1);
        listView1.setXListViewListener(new XListView.IXListViewListener() {
            @Override
            public void onRefresh() {
                pageIndex1 = 1;
                adapter1.clear();
                ProductList.ProductItem item = new ProductList.ProductItem();
                item.setItemName("序列号");
                item.setType(1);
                adapter1.addItem(item);
                adapter1.notifyDataSetChanged();
                requestList(false, 0);
            }

            @Override
            public void onLoadMore() {
                requestList(false, 0);
            }
        });
        listView1.setOnScrollListener(scrollListener);
        listView2 = (ObservableXListView) view.findViewById(R.id.ics_listView);
        listView2.setXListViewListener(new XListView.IXListViewListener() {
            @Override
            public void onRefresh() {
                pageIndex2 = 1;
                adapter2.clear();
                ProductList.ProductItem item = new ProductList.ProductItem();
                item.setItemName("批号");
                item.setType(1);
                adapter2.addItem(item);
                adapter2.notifyDataSetChanged();
                requestList(false, 1);
            }

            @Override
            public void onLoadMore() {
                requestList(false, 1);
            }
        });
        listView2.setAdapter(adapter2);
        listView2.setVisibility(View.GONE);
        listView2.setOnScrollListener(scrollListener);
        GridView gridView = (GridView) view.findViewById(R.id.seg);
        final TwSegmentWidget widget = new TwSegmentWidget(gridView, new String[]{"有码", "无码"}, null, true, 1);
        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                if (i == 0) {
                    listView1.setVisibility(View.VISIBLE);
                    listView2.setVisibility(View.GONE);
                    if (adapter1.getCount() == 0) {
                        requestList(true, 0);
                    }
                } else {
                    listView1.setVisibility(View.GONE);
                    listView2.setVisibility(View.VISIBLE);
                    if (adapter2.getCount() == 0) {
                        ProductList.ProductItem item = new ProductList.ProductItem();
                        item.setItemName("批号");
                        item.setType(1);
                        adapter2.addItem(item);
                        adapter2.notifyDataSetChanged();
                        requestList(true, 1);
                    }
                }
                widget.choose(i);
            }
        });
        requestList(true, 0);
    }

    @Override
    public int layoutId() {
        return R.layout.product_detail;
    }

    private void requestList(boolean show, final int type) {
        if (show) {
            showLoadImg();
        }
        Map<String, String> param = new HashMap<>();
        param.put("itemCode", item.getItemCode());
        param.put("itemType", String.valueOf(type));
        if(whName.contains("库")){
            param.put("reqType","1");
        }else{
            param.put("reqType","2");
        }
        param.put("pageIndex", type == 0 ? String.valueOf(pageIndex1) : String.valueOf(pageIndex2));
        param.put("pageSize", String.valueOf(Constant.PAGE_SIZE));
        getHttpClient().post().url(Constant.PRODUCT_COUNTINFO_LIST).params(Constant.makeParam(param)).build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int i) {
                dismissLoadImg();
                if (type == 0) {
                    listView1.stopRefresh();
                    listView1.stopLoadMore();
                } else {
                    listView2.stopRefresh();
                    listView2.stopLoadMore();
                }
                Utils.showToast(getContext(), R.string.server_error);
            }

            @Override
            public void onResponse(String s, int i) {
                dismissLoadImg();
                if (type == 0) {
                    listView1.stopRefresh();
                    listView1.stopLoadMore();
                } else {
                    listView2.stopRefresh();
                    listView2.stopLoadMore();
                }
                Type mType = new TypeToken<BaseObjResponse<ProductList>>() {
                }.getType();
                BaseObjResponse<ProductList> response = new Gson().fromJson(s, mType);
                if ("1".equals(response.getResult().getCode())) {
                    if (type == 0) {
                        adapter1.addAll(response.getResult().getProductList());
                        adapter1.notifyDataSetChanged();
                        if (response.getResult().getProductList().size() == Constant.PAGE_SIZE) {
                            pageIndex1++;
                            listView1.setPullLoadEnable(true);
                        } else {
                            listView1.setPullLoadEnable(false);
                        }
                    } else {
                        adapter2.addAll(response.getResult().getProductList());
                        adapter2.notifyDataSetChanged();
                        if (response.getResult().getProductList().size() == Constant.PAGE_SIZE) {
                            pageIndex2++;
                            listView2.setPullLoadEnable(true);
                        } else {
                            listView2.setPullLoadEnable(false);
                        }
                    }
                } else {
                    Utils.showToast(getContext(), response.getResult().getMsg());
                }
            }
        });
    }

    private void refershNum() {
        numView.setText(String.valueOf(CacheTool.getInputCount(getContext()) + CacheTool.getOutputCount(getContext())));
    }

    @Subscribe
    public void onEventMainThread(RefershEvent event) {
        if (event.mclass == this.getClass()) {
            refershNum();
            if (event.bundle != null && event.bundle.getBoolean("refersh", false)) {
                if (listView1.getVisibility() == View.VISIBLE) {
                    pageIndex1 = 1;
                    adapter1.clear();
                    ProductList.ProductItem item = new ProductList.ProductItem();
                    item.setItemName("序列号");
                    item.setType(1);
                    adapter1.addItem(item);
                    adapter1.notifyDataSetChanged();
                    requestList(true, 0);
                } else {
                    pageIndex2 = 1;
                    adapter2.clear();
                    ProductList.ProductItem item = new ProductList.ProductItem();
                    item.setItemName("批号");
                    item.setType(1);
                    adapter2.addItem(item);
                    adapter2.notifyDataSetChanged();
                    requestList(true, 1);
                }
            }
        }
    }

    private class ItemAdapter extends EnhancedAdapter<ProductList.ProductItem> {

        private View.OnClickListener btnListener = new View.OnClickListener() {
            @Override
            public void onClick(final View view) {
                new TwDialogBuilder(getContext()).setItems(new String[]{"入库", "出库"}, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        ProductList.ProductItem item = (ProductList.ProductItem) view.getTag();
                        if (!item.getStatus().equals("在库") && i == 2) {
                            Utils.showToast(getContext(), "产品不在库，不可出库");
                            return;
                        }
                        ProductList.ProductItem newItem = new ProductList.ProductItem();
                        newItem.setMaterialName(item.getMaterialName());
                        newItem.setMaterialNumber(item.getMaterialNumber());
                        newItem.setSerialNumber(item.getSerialNumber());
                        newItem.setLots(item.getBatchNumber());
                        newItem.setSubBU(item.getSubBU());
                        newItem.setUom(item.getSaleUnit());
                        newItem.setQty(item.getQty());
                        newItem.setNowqty(item.getQty());
                        newItem.setProductId(item.getProductId());
                        newItem.setExpDate(item.getExpDate());
                        newItem.setDomDate(item.getDomDate());
                        newItem.setDistCode(item.getDistCode());
                        newItem.setDistName(item.getDistName());
                        ProductList.ProductItem result = null;
                        result = CacheTool.append(getContext(), newItem, i);
                        if (result == null) {
                            Utils.showToast(getContext(), "已添加!");
                            return;
                        }
                        refershNum();
                        RefershEvent event = new RefershEvent();
                        event.mclass = ProductFragment.class;
                        EventBus.getDefault().post(event);
                        Utils.showToast(getContext(), "添加成功!");
                        Utils.showToast(getContext(), "添加成功");
                        refershNum();
                    }
                }, "").create().show();

            }
        };
        private View.OnClickListener itemListener = new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ProductList.ProductItem item = (ProductList.ProductItem) view.getTag(R.id.button1);
                Bundle bundle = new Bundle();
                bundle.putInt("type", 2);
                bundle.putSerializable("model", item);
                FragmentUtil.navigateToInNewActivity(getActivity(), ProductInfoFragment.class, bundle);
            }
        };
        private SwipeMenuLayout currentSwipeLayout;
        private SwipeSwitchListener swipeListener = new SwipeSwitchListener() {
            @Override
            public void beginMenuClosed(SwipeMenuLayout swipeMenuLayout) {
//                ProductList.ProductItem item = (ProductList.ProductItem) swipeMenuLayout.getTag(R.id.button1);
//                item.setArror(0);
            }

            @Override
            public void beginMenuOpened(SwipeMenuLayout swipeMenuLayout) {
                if (currentSwipeLayout != null && swipeMenuLayout != currentSwipeLayout) {
                    currentSwipeLayout.smoothCloseBeginMenu();
                }
                currentSwipeLayout = swipeMenuLayout;
//                ProductList.ProductItem item = (ProductList.ProductItem) swipeMenuLayout.getTag(R.id.button1);
//                item.setArror(1);
            }

            @Override
            public void endMenuClosed(SwipeMenuLayout swipeMenuLayout) {
//                ProductList.ProductItem item = (ProductList.ProductItem) swipeMenuLayout.getTag(R.id.button1);
//                item.setArror(2);
            }

            @Override
            public void endMenuOpened(SwipeMenuLayout swipeMenuLayout) {
//                ProductList.ProductItem item = (ProductList.ProductItem) swipeMenuLayout.getTag(R.id.button1);
//                item.setArror(3);
                if (currentSwipeLayout != null && swipeMenuLayout != currentSwipeLayout) {
                    currentSwipeLayout.smoothCloseEndMenu();
                }
                currentSwipeLayout = swipeMenuLayout;
            }
        };
        public ItemAdapter(Context context) {
            super(context);
        }

        public void closeSlide() {
            if (currentSwipeLayout != null) {
                try {
                    currentSwipeLayout.smoothCloseBeginMenu();
                    currentSwipeLayout.smoothCloseEndMenu();
                    currentSwipeLayout = null;
                } catch (Exception e) {

                }
            }
        }

        @Override
        protected void bindView(View paramView, Context paramContext, int position) {
            ViewHolder holder = (ViewHolder) paramView.getTag();
            int type = getItemViewType(position);
            ProductList.ProductItem item = getItem(position);
            if (type == 1) {
                holder.titleView.setText(item.getItemName());
            } else {
                if (listView1.getVisibility() == View.VISIBLE) {
                    holder.titleView.setText(item.getSerialNumber());
                    holder.textView.setVisibility(View.VISIBLE);
                    holder.descView.setText(String.format("%s %s", item.getQty(), item.getUom()));
                } else {
                    if (!TextUtils.isEmpty(item.getLots())) {
                        holder.titleView.setText(item.getLots());
                    } else {
                        holder.titleView.setText("序列号、批号未知产品");
                    }
                }
                holder.btnView.setTag(item);
                if (TextUtils.isEmpty(item.getExpDate())) {
                    holder.textView.setVisibility(View.GONE);
                } else {
                    holder.textView.setVisibility(View.VISIBLE);
                    holder.textView.setText("失效期 " + item.getExpDate());
                }
                paramView.setTag(R.id.button1, item);
            }
        }

        @Override
        protected View newView(Context context, int position, ViewGroup viewgroup) {
            int type = getItemViewType(position);
            View rootView = null;
            if (type == 1) {
                TextView textView = new TextView(context);
                textView.setTextColor(ContextCompat.getColor(getContext(), R.color.text_gray));
                textView.setTextSize(12);
                int padding = Utils.convertDIP2PX(context, 15);
                textView.setPadding(padding, padding / 2, padding, padding / 2);
                rootView = textView;
                ViewHolder holder = new ViewHolder();
                holder.titleView = textView;
                rootView.setTag(holder);
            } else {
                rootView = inflater.inflate(R.layout.product_detail_item, viewgroup, false);
                SwipeHorizontalMenuLayout layout = (SwipeHorizontalMenuLayout) rootView;
                layout.setSwipeListener(swipeListener);
                ViewHolder holder = new ViewHolder();
                holder.titleView = (TextView) rootView.findViewById(R.id.title);
                holder.descView = (TextView) rootView.findViewById(R.id.desc);
                holder.textView = (TextView) rootView.findViewById(R.id.text);
                holder.btnView = (TextView) rootView.findViewById(R.id.smMenuViewLeft);
                holder.btnView.setOnClickListener(btnListener);
                rootView.setOnClickListener(itemListener);
                rootView.setTag(holder);
            }
            return rootView;
        }

        @Override
        public int getItemViewType(int position) {
            return getItem(position).getType();
        }

        @Override
        public int getViewTypeCount() {
            return 2;
        }

    }

    private class ViewHolder {
        TextView titleView, descView, textView, btnView;
    }
}
